<template>
  <div class='page-container'>
    <div class="stage" ref="stage"></div>
    <div class="control-wrap">
      <div class="btn-wrap">
        <div class="btn up" @touchstart="handleUp($event,'press')" @touchend="handleUp($event, 'release')"></div>
        <div class="btn right" @touchstart="handleRight($event, 'press')" @touchend="handleRight($event, 'release')"></div>
        <div class="btn left" @touchstart="handleLeft($event, 'press')" @touchend="handleLeft($event, 'release')"></div>
        <div class="btn down" @touchstart="handleDown($event,'press')" @touchend="handleDown($event, 'release')"></div>
      </div>
    </div>
  </div>
</template>
<script>
// import * as PIXI from 'pixi.js'
import { Application, Container, loader, resources, Graphics, TextureCache, Sprite, Text, TextStyle, InteractionEvent} from 'pixi.js'
import { randomInt, contain, hitTestRectangle } from './js/utils'
let state, explorer, treasure, blobs, chimes, exit, player, dungeon,
    door, healthBar, message, gameScene, gameOverScene, enemies, id;
let up,
    down,
    left,
    right;
export default {
  name: 'TreasureHunter',
  components: {},
  computed: {},
  data() {
    return {
      app: null,
    }
  },
  created() {

  },
  mounted() {
    this.initApp()
  },
  beforeDestroy() {
  },
  methods: {
    initApp() {
      const devicePixelRatio = window.devicePixelRatio

      this.app = new Application({
            width: 512,
            height: 512,
            antialiasing: true,
            transparent: false,
            resolution: devicePixelRatio
          });
      this.$refs['stage'].appendChild(this.app.view)


      loader
          .add("http://oss.gylm.club/pixi/images/treasureHunter.json")
          .on("progress", (loader, resource) => {
            console.log(loader)
            console.log(resource)
          })
          .on('error', (err) => {
            console.log(err)
          })
          .load(this.setup);
    },

    setup() {
      // Initialize the game sprites, set the game `state` to `play`(初始化游戏精灵，设置游戏状态)
      //and start the 'gameLoop'(开始循环更新)

      //Create the `gameScene` group(创建游戏场景)
      gameScene = new Container();
      this.app.stage.addChild(gameScene);


      id = loader.resources["http://oss.gylm.club/pixi/images/treasureHunter.json"].textures;
      // Dungeon
      dungeon = new Sprite(id["dungeon.png"]);

      gameScene.addChild(dungeon);
      //Create the `door` sprite(创建门精灵)
      door = new Sprite(id["door.png"]);
      door.position.set(32, 0);
      gameScene.addChild(door);


      //Explorer (创建探险家)
      explorer = new Sprite(id["explorer.png"]);
      explorer.x = 68;
      explorer.y = gameScene.height / 2 - explorer.height / 2;
      explorer.vx = 0;
      explorer.vy = 0;
      gameScene.addChild(explorer);

      //Treasure （创建宝箱）
      treasure = new Sprite(id["treasure.png"]);
      treasure.x = gameScene.width - treasure.width - 48;
      treasure.y = gameScene.height / 2 - treasure.height / 2;
      gameScene.addChild(treasure);

      //Make the blobs
      let numberOfBlobs = 6,
          spacing = 48,
          xOffset = 150,
          speed = 2,
          direction = 1;

      //An array to store all the blob monsters
      blobs = [];

      //Make as many blobs as there are `numberOfBlobs`
      for (let i = 0; i < numberOfBlobs; i++) {

        //Make a blob
        let blob = new Sprite(id["blob.png"]);

        //Space each blob horizontally according to the `spacing` value.
        //`xOffset` determines the point from the left of the screen
        //at which the first blob should be added
        let x = spacing * i + xOffset;

        //Give the blob a random y position
        let y = randomInt(0, this.app.stage.height - blob.height);

        //Set the blob's position
        blob.x = x;
        blob.y = y;

        //Set the blob's vertical velocity. `direction` will be either `1` or
        //`-1`. `1` means the enemy will move down and `-1` means the blob will
        //move up. Multiplying `direction` by `speed` determines the blob's
        //vertical direction
        blob.vy = speed * direction;

        //Reverse the direction for the next blob
        direction *= -1;

        //Push the blob into the `blobs` array
        blobs.push(blob);

        //Add the blob to the `gameScene`
        gameScene.addChild(blob);
      }


      //Create the health bar
      healthBar = new Container();
      healthBar.position.set(this.app.stage.width - 170, 4)
      gameScene.addChild(healthBar);

      let hbTextStyle = new TextStyle({
        fontFamily: "Futura",
        fontSize: 24,
        fill: "0xFF3300"
      });
      let hbText = new Text("Hb", hbTextStyle);
      hbText.x= -hbText.width
      hbText.y= -10
      healthBar.addChild(hbText);

      //Create the black background rectangle
      let innerBar = new Graphics();
      innerBar.beginFill(0x000000);
      innerBar.drawRect(0, 0, 128, 8);
      innerBar.endFill();
      healthBar.addChild(innerBar);

      //Create the front red rectangle
      let outerBar = new Graphics();
      outerBar.beginFill(0xFF3300);
      outerBar.drawRect(0, 0, 128, 8);
      outerBar.endFill();
      healthBar.addChild(outerBar);
      healthBar.outer = outerBar;

      //Create the `gameOver` scene
      gameOverScene = new Container();
      this.app.stage.addChild(gameOverScene);
      //Make the `gameOver` scene invisible when the game first starts
      gameOverScene.visible = false;

      //Create the text sprite and add it to the `gameOver` scene
      let style = new TextStyle({
        fontFamily: "Futura",
        fontSize: 64,
        fill: "white"
      });
      message = new Text("The End!", style);
      message.x = 120;
      message.y = this.app.stage.height / 2 - 32;

      gameOverScene.addChild(message);

      //Capture the keyboard arrow keys
      left = this.keyboard(37);
      up = this.keyboard(38);
      right = this.keyboard(39);
      down = this.keyboard(40);
      //Left arrow key `press` method
      //Left arrow key `press` method
      left.press = function() {

        //Change the explorer's velocity when the key is pressed
        explorer.vx = -5;
        explorer.vy = 0;
      };

      //Left arrow key `release` method
      left.release = function() {

        //If the left arrow has been released, and the right arrow isn't down,
        //and the explorer isn't moving vertically:
        //Stop the explorer
        if (!right.isDown && explorer.vy === 0) {
          explorer.vx = 0;
        }
      };

      //Up
      up.press = function() {
        explorer.vy = -5;
        explorer.vx = 0;
      };
      up.release = function() {
        if (!down.isDown && explorer.vx === 0) {
          explorer.vy = 0;
        }
      };

      //Right
      right.press = function() {
        explorer.vx = 5;
        explorer.vy = 0;
      };
      right.release = function() {
        if (!left.isDown && explorer.vy === 0) {
          explorer.vx = 0;
        }
      };

      //Down
      down.press = function() {
        explorer.vy = 5;
        explorer.vx = 0;
      };
      down.release = function() {
        if (!up.isDown && explorer.vx === 0) {
          explorer.vy = 0;
        }
      };


      // set the game state to `play`
      state = this.play;

      //Start the game loop
      this.app.ticker.add(delta => this.gameLoop(delta));
    },

    gameLoop(delta){
      //Update the current game state:
      state(delta);
    },

    play(delta) {
      //All the game logic goes here
      //use the explorer's velocity to make it move
      explorer.x += explorer.vx;
      explorer.y += explorer.vy;

      //Contain the explorer inside the area of the dungeon
      contain(explorer, {x: 28, y: 10, width: 488, height: 480});
      //contain(explorer, stage);

      //Set `explorerHit` to `false` before checking for a collision
      let explorerHit = false;

      //Loop through all the sprites in the `enemies` array
      blobs.forEach(function(blob) {

        //Move the blob
        blob.y += blob.vy;

        //Check the blob's screen boundaries
        let blobHitsWall = contain(blob, {x: 28, y: 10, width: 488, height: 480});

        //If the blob hits the top or bottom of the stage, reverse
        //its direction
        if (blobHitsWall === "top" || blobHitsWall === "bottom") {
          blob.vy *= -1;
        }

        //Test for a collision. If any of the enemies are touching
        //the explorer, set `explorerHit` to `true`
        if(hitTestRectangle(explorer, blob)) {
          explorerHit = true;
        }
      });

      //If the explorer is hit...
      if(explorerHit) {

        //Make the explorer semi-transparent
        explorer.alpha = 0.5;

        //Reduce the width of the health bar's inner rectangle by 1 pixel
        healthBar.outer.width -= 1;

      } else {

        //Make the explorer fully opaque (non-transparent) if it hasn't been hit
        explorer.alpha = 1;
      }

      //Check for a collision between the explorer and the treasure
      if (hitTestRectangle(explorer, treasure)) {

        //If the treasure is touching the explorer, center it over the explorer
        treasure.x = explorer.x + 8;
        treasure.y = explorer.y + 8;
      }

      //Does the explorer have enough health? If the width of the `innerBar`
      //is less than zero, end the game and display "You lost!"
      if (healthBar.outer.width < 0) {
        state = this.end;
        message.text = "You lost!";
      }

      //If the explorer has brought the treasure to the exit,
      //end the game and display "You won!"
      if (hitTestRectangle(treasure, door)) {
        state = this.end;
        message.text = "You won!";
        message.interactive = true;//响应交互
        message.on("pointerdown", (event) => {
          window.location.reload()
        })
      }
    },

    end() {
      gameScene.visible = false;
      gameOverScene.visible = true;
    },

    keyboard(keyCode) {
      var key = {};
      key.code = keyCode;
      key.isDown = false;
      key.isUp = true;
      key.press = undefined;
      key.release = undefined;
      //The `downHandler`
      key.downHandler = function(event) {
        if (event.keyCode === key.code) {
          if (key.isUp && key.press) key.press();
          key.isDown = true;
          key.isUp = false;
        }
        event.preventDefault();
      };

      //The `upHandler`
      key.upHandler = function(event) {
        if (event.keyCode === key.code) {
          if (key.isDown && key.release) key.release();
          key.isDown = false;
          key.isUp = true;
        }
        event.preventDefault();
      };

      //Attach event listeners
      window.addEventListener(
          "keydown", key.downHandler.bind(key), false
      );
      window.addEventListener(
          "keyup", key.upHandler.bind(key), false
      );
      return key;
    },
    handleUp(event, type) {
      if(type === 'press') {
        explorer.vy = -5;
        explorer.vx = 0;
      }
      if(type === 'release'){
        if (!down.isDown && explorer.vx === 0) {
          explorer.vy = 0;
        }
      }
      event.preventDefault();
    },
    handleDown(event, type) {
      if(type === 'press') {
        explorer.vy = 5;
        explorer.vx = 0;
      }
      if(type === 'release'){
        if (!up.isDown && explorer.vx === 0) {
          explorer.vy = 0;
        }
      }
      event.preventDefault();
    },
    handleLeft(event, type) {
      if(type === 'press') {
        explorer.vx = -5;
        explorer.vy = 0;
      }
      if(type === 'release'){
        if (!right.isDown && explorer.vy === 0) {
          explorer.vx = 0;
        }
      }
      event.preventDefault();
    },
    handleRight(event, type) {
      if(type === 'press') {
        explorer.vx = 5;
        explorer.vy = 0;
      }
      if(type === 'release'){
        if (!left.isDown && explorer.vy === 0) {
          explorer.vx = 0;
        }
      }
      event.preventDefault();
    },
  }
}
</script>

<style scoped lang="less">
.page-container {
  user-select: none;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .stage {
    width: 100%;
    /deep/
    canvas {
      display: block;
      margin: 0 auto;
      max-width: 500PX;
      width: 100%;
    }
  }
  .control-wrap {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    .btn-wrap {
      max-width: 280PX;
      max-height: 280PX;
      width: 280px;
      height: 280px;
      display: flex;
      flex-wrap: wrap;
      align-content: space-between;
      justify-content: space-between;
      transform: rotate(45deg);
    }
    .btn {
      touch-action: none;
      width: 42%;
      height: 42%;
      position: relative;
      color: #FFFFFF;
      border-radius: 10px;
      background-color: #4e6ef2;
      &:nth-child(2n+1) {

      }
      &::before {
        content: '';
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #FFFFFF;
        font-size: 28px;
        font-weight: bold;
        position: absolute;
        top: 0;
        left: 0;
        transform: rotate(-45deg);
      }
      &.up::before {
        content: 'up';
      }
      &.down::before {
        content: 'down';
      }
      &.left::before {
        content: 'left';
      }
      &.right::before {
        content: 'right';
      }
    }

  }
}
</style>
